<?php
/**
 * Created by PhpStorm.
 * User: yiyu
 * Email: smalleasyu@gmail.com
 * Date: 2020-01-19 22:24:50
 * Desc:
 */

namespace app\api\service\MiniProgram;

use app\base\service\BaseService;
use app\base\model\user\UserWx;
use function Clue\StreamFilter\fun;
use EasyWeChat\Factory;
use app\core\exception\BusinessException;
use app\core\exception\ErrorCode;
use app\core\log\Log4dd;

class MiniProgramBaseService extends BaseService
{

    public static function getMiniProgramOpenIds($config, $code)
    {
        if (!isset($config['app_id'], $config['secret']) || empty($config['app_id']) || empty($config['secret'])) {
            Log4dd::error('小程序初始化失败,app_id配置错误', func_get_args());
            throw new BusinessException(ErrorCode::COMMON_ERROR, '小程序参数配置错误');
        }

        $app = Factory::miniProgram($config);

        $result = $app->auth->session($code);

        Log4dd::info('小程序初始化,获取open_id，返回数据', [func_get_args(), $result]);

        /*if (empty($result) || !isset($result['errcode'])) {
            throw new BusinessException(ErrorCode::COMMON_ERROR, '请求微信服务器失败,请稍后再试');
        }

        if ($result['errcode'] != 0) {
            throw new BusinessException($result['errcode'], ($result['errmsg'] ?? '请求微信服务器失败,请稍后再试'));
        }*/

        if (!isset($result['session_key'])) {
            throw new BusinessException(ErrorCode::COMMON_ERROR, '获取session_key失败,请稍后再试');
        }

        if (!isset($result['openid'])) {
            throw new BusinessException(ErrorCode::COMMON_ERROR, '获取opneid失败,请稍后再试');
        }

        UserWx::saveMiniProgramSessionKey($result['openid'], $result['session_key']);

        return [
            'openId' => $result['openid'],
            'unionId' => $result['unionid'] ?? '',
        ];

    }


    public static function getMiniProgramUserInfo($config, $open_id, $data)
    {
        Log4dd::info('解密微信小程序用户信息参数：' . $open_id, func_get_args());
        if (!isset($config['app_id'], $config['secret']) || empty($config['app_id']) || empty($config['secret'])) {
            throw new BusinessException(ErrorCode::COMMON_ERROR, '小程序参数错误');
        }

        $app = Factory::miniProgram($config);

        $session_key = UserWx::getSessionKeyByOpenId($open_id);

        if (empty($session_key)) {
            throw new BusinessException(ErrorCode::MINI_PROGRAM_SESSION_KEY_EXPIRE);
        }

        $decryptedData = $app->encryptor->decryptData($session_key, $data['iv'], $data['encryptedData']);


        if (!isset($decryptedData['openId']) || empty($decryptedData['openId'])) {
            throw new BusinessException(ErrorCode::COMMON_ERROR, '解密数据失败,请稍后再试');
        }

        Log4dd::info('解密微信小程序用户信息结果：' . $open_id, $decryptedData);
        return $decryptedData;

    }

}